package org.xm.moretriggercommands.Event;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.xm.moretriggercommands.Main;

import java.text.SimpleDateFormat;
import java.util.Date;

public class PlayerDeath implements Listener {

    @EventHandler
    public void onPlayerDeath(PlayerDeathEvent e) {
        if (Main.getInstance().getConfig().getBoolean("PlayerDeath.Switch", false)) {
            String command_console_cd = Main.getInstance().getConfig().getString("PlayerDeath.Console-Command-Cd");
            String player_console_cd = Main.getInstance().getConfig().getString("PlayerDeath.Player-Command-Cd");
            Player player = e.getEntity();
            for (String cmd : Main.getInstance().getConfig().getStringList("PlayerDeath.Console-Commands"))
                //创建Bukkit调度管理器，并延迟
                Bukkit.getScheduler().runTaskLater(Main.getInstance(), new Runnable() {
                    public void run() {
                        Bukkit.dispatchCommand(Main.getInstance().getServer().getConsoleSender(), translatePlaceholders(cmd, player, e));
                    }
                }, Long.parseLong(command_console_cd));

            for (String cmd : Main.getInstance().getConfig().getStringList("PlayerDeath.Player-Commands")) {
                //创建Bukkit调度管理器，并延迟
                Bukkit.getScheduler().runTaskLater(Main.getInstance(), new Runnable() {
                    public void run() {
                        Bukkit.dispatchCommand(e.getEntity(), translatePlaceholders(cmd, player, e));
                    }
                }, Long.parseLong(player_console_cd));
            }
        }
    }
    private String translatePlaceholders(String cmd, Player player, PlayerDeathEvent e ) {
        Location location = player.getLocation();
        int deathNumber = player.getStatistic(Statistic.DEATHS);
        Date day=new Date();
        String date = Main.getInstance().getConfig().getString("PlayerDeath.Date");
        SimpleDateFormat df = new SimpleDateFormat(date);
        return cmd.replaceAll("%player_name%", player.getName())
                .replaceAll("%x%", Integer.toString(location.getBlockX()))
                .replaceAll("%y%", Integer.toString(location.getBlockY()))
                .replaceAll("%z%", Integer.toString(location.getBlockZ()))
                .replaceAll("%world%", location.getWorld().getName())
                .replaceAll("%DeathMsg%", e.getDeathMessage())
                .replaceAll("%DeathNumber%", Integer.toString(deathNumber))
                .replaceAll("%Deathdate%", df.format(day))
                .replaceAll("&", "§");
    }

}